package com.hzqy.web.ac.pms;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.hzqy.commons.utils.*;
import com.hzqy.service.hotel.WechatHotelService;
import com.hzqy.service.wchat.WechatWXService;
import com.hzqy.web.ac.WchatAction;
import com.hzqy.web.vo.*;
import com.hzqy.web.vo.pms.PmsLoginAspectVo;
import com.hzqy.web.vo.wchat.LoginMessage.ReceiveMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hzqy.service.pms.PmsServiceBean;

import static java.lang.Integer.parseInt;

@Controller
@RequestMapping("/")
public class PmsAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private PmsServiceBean pmsServiceBean;
	@Resource
	WechatHotelService wechatHotelService;
	@Resource
	WechatWXService wechatWXService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields(new String[]{"admin"});
	}
	@RequestMapping("login")
	public Object login(ModelMap map,String f_pu_name,String f_pu_pwd,String recode,HttpSession session,HttpServletRequest request){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String title = session.getServletContext().getInitParameter("title");
		resultMap.put("title", title);
		String code = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,null);
		if(f_pu_name==null && f_pu_pwd==null && recode==null) {//登录
			resultMap.put("status", "login"); //请不要修改此值，会关联引用到PmsAspect类中的安全判断--dpf 2018-10-24
			return resultMap;
		}
		PmsUserVo puv = new PmsUserVo();
		puv.setF_pu_name(f_pu_name);
		ServletContext application = session.getServletContext();
		Object applicationLoginFailLockObject = application.getAttribute("applicationLoginFailLockHashMap");
		HashMap<String,ArrayList<PmsLoginAspectVo>> applicationLoginFailLockHashMap = null;
		if(applicationLoginFailLockObject==null)
			applicationLoginFailLockHashMap = new HashMap<String,ArrayList<PmsLoginAspectVo>>();
		else {
			applicationLoginFailLockHashMap = (HashMap<String,ArrayList<PmsLoginAspectVo>>)applicationLoginFailLockObject;
		}
		ArrayList<PmsLoginAspectVo> loginFailLockCountList = applicationLoginFailLockHashMap.get(f_pu_name);
		if(loginFailLockCountList == null)
			loginFailLockCountList = new ArrayList<PmsLoginAspectVo>();
		String loginFailLockCountStr = SystemConfigUtils.getSysConfig("system_login_fail_lock_count");
		int loginFailLockCount = 5;
		if(loginFailLockCountStr != null && !loginFailLockCountStr.trim().equals(""))
			loginFailLockCount = Integer.parseInt(loginFailLockCountStr);
		if(loginFailLockCountList.size()>=loginFailLockCount-1) {
			//登录失败次数过多冻结账号
			PmsUserVo userVo = pmsServiceBean.findUserByName(puv);
			if(userVo == null || userVo.getRoleIds() == null || userVo.getRoleIds().trim().length()==0){
				resultMap.put("status", "error");
				resultMap.put("msg", "用户名错误!");
				return resultMap;
			}else{
				userVo.setF_pu_status(2);
				pmsServiceBean.updateUserStatus(userVo);
				resultMap.put("status", "error");
				resultMap.put("msg", "用户连续登录失败次数已达到限制,已冻结。");
				return resultMap;
			}
		}
		LOG.debug("code=="+code);
		LOG.debug("recode=="+recode);


		if(recode == null || !recode.trim().equals(code)) {
			resultMap.put("status", "error");
			resultMap.put("msg", "图形验证码错误!");
			return resultMap;
		}
		puv.setF_pu_pwd(f_pu_pwd);
		PmsUserVo userVo = pmsServiceBean.findUser(puv);
		if(userVo == null || userVo.getRoleIds() == null || userVo.getRoleIds().trim().length()==0) {
			resultMap.put("status", "error");
			resultMap.put("msg", "用户名或密码错误!");
			return resultMap;
		}
		String user_ip="";
		try {
			user_ip=HttpGetData.getIpAddr(request);
			session.setAttribute(ConstantUtils.SESSION_USER_IP, user_ip);
		} catch (Exception e) {
			LOG.error("获取ip地址错误",e);
		}

		//管理员角色配置项
		String admin_roleList = SystemConfigUtils.getSysConfig("admin_roleList");
		String[] roleList=admin_roleList.split(",");
		boolean isAdmin=false;
		for (int i = 0; i < roleList.length; i++) {
			String roles=userVo.getRoleIds();
			String[] roleArr = roles.split(",");
			for (int j = 0; j < roleArr.length; j++) {
				if (roleList[i].equals(""+roleArr[j])){
					isAdmin=true;
					break;
				}
			}
		}
		//如果是管理员登录，需要开启ip白名单
		if(isAdmin){
			//管理员ip白名单
			String admin_ipList = SystemConfigUtils.getSysConfig("admin_ipList");
			String[] ipList=admin_ipList.split(",");
			boolean flag=false;
			try {
				//获取用户ip
				String ip = user_ip;
				LOG.debug("user_ip="+user_ip);
				for (int i = 0; i < ipList.length; i++) {
					if(ip.contains(ipList[i])){
						flag=true;
						break;
					}
				}
			}catch (Exception e) {
				LOG.debug("获取用户ip异常");
				e.printStackTrace();
			}
			if (!flag) {
				resultMap.put("status", "error");
				resultMap.put("msg", "未开启管理员ip白名单！");
				return resultMap;
			}
		}

		String pwd_date = SystemConfigUtils.getSysConfig("pwd_date");
		userVo.setPwd_date(parseInt(pwd_date));
		userVo.setF_pu_id(userVo.getF_pu_id());
		int historyPWdCount = pmsServiceBean.findUserHistoryPWdCount(userVo);
		if(historyPWdCount==0){
			resultMap.put("status", "error");
			resultMap.put("msg", parseInt(pwd_date)+"天内未更换密码!");
			//未按时更新密码冻结账号
			userVo.setF_pu_status(2);
			pmsServiceBean.updateUserStatus(userVo);
			return resultMap;
		}
		userVo.setPwd_date(1);
		//int retryCounts = pmsServiceBean.findUserHistoryPWdCount(userVo);
		String message_switch = SystemConfigUtils.getSysConfig("message_switch");
		if("1".equals(message_switch)){
			ReceiveMessage sms =new ReceiveMessage();
			//String login_type = SystemConfigUtils.getSysConfig("login_type");
			String login_type="1";
			sms.setLogin_type(login_type);
			sms.setSmsType(3);
			sms.setPhones(userVo.getF_pu_phone());
			SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd ");
			Date date = new Date();
			String dats = df1.format(date);
			String startTime=dats+" 00:00:00";
			String endTime=dats+" 23:59:59";
			sms.setStartTime(startTime);
			sms.setEndTime(endTime);
			int retryCounts=wechatWXService.selectRSMSCount(sms);
			if(retryCounts>parseInt(SystemConfigUtils.getSysConfig("pwd_set_times"))){
				resultMap.put("status", "error");
				resultMap.put("msg", "今日重置次数达到上限!");
				//重置次数达到上限冻结账号
				userVo.setF_pu_status(2);
				pmsServiceBean.updateUserStatus(userVo);
				return resultMap;
			}
		}

		List<PmsAttributeVo> pavList= pmsServiceBean.selectAttributeList(userVo);
		session.setAttribute(ConstantUtils.SESSION_ATTRIBUTE, pavList);
		List<PmsResourceVo> resourceList = pmsServiceBean.selectUserResourceList(userVo);
		session.setAttribute(ConstantUtils.SESSION_RESOURCE, resourceList);
		session.setAttribute(ConstantUtils.SESSION_USER, userVo);
		resultMap.put("status", "success");
		return "redirect:main.do";
	}
	@RequestMapping("hotel_loginOut")
	public String hotelPCLoginOut(HttpSession session){
		session.removeAttribute(ConstantUtils.SESSION_USER);
		session.invalidate();
		return "redirect:hotel_login.do";
	}
	
	@RequestMapping("loginOut")
	public String loginOut(HttpSession session){
		session.removeAttribute(ConstantUtils.SESSION_USER);
		session.invalidate();
		return "redirect:login.do";
	}
	
    @RequestMapping("/pms/left")
	@ResponseBody
    public Object left(HttpSession session){
    	PmsUserVo puv = (PmsUserVo)session.getAttribute(ConstantUtils.SESSION_USER);
    	List<PmsResourceVo> resourceList = pmsServiceBean.findUserResourcesByRoleId(puv);
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("menus", resourceList);
        return map;
    }
	
	@RequestMapping("hotel/pc/hotel_main")
	public Object hotel_pc_main(ModelMap map, HttpSession session){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String title = session.getServletContext().getInitParameter("title");
		map.put("title", title);
		return resultMap;
	}
	
	@RequestMapping("main")
	public Object main(ModelMap map, HttpSession session){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String title = session.getServletContext().getInitParameter("title");
		map.put("title", title);
		return resultMap;
	}
	
	@RequestMapping("/pms/update_password")
	@ResponseBody
	public Object updatePassword(PmsUserVo puv,String f_pu_oldPwd) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		boolean isOldPwd = pmsServiceBean.checkOldPwd(puv,f_pu_oldPwd);
		if(isOldPwd){//原密码正确
			int flag = pmsServiceBean.updatePassword(puv);
			if(flag >0) {
				resultMap.put("success", true);
				resultMap.put("result","密码修改成功!");
			} else {
				resultMap.put("success", false);
				resultMap.put("result","密码修改失败!");
			}
		} else {
			resultMap.put("success", false);
			resultMap.put("result","原密码错误!");
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/user_show")
	@ResponseBody
	public Object userShow(HttpSession session,ModelMap map,int f_pu_id,PmsUserVo userVo){
		PmsUserVo puv = pmsServiceBean.findUserById(session,userVo,f_pu_id);
		map.put("user", puv);
		if(puv==null){
			Map<String,Object> resultMap = new HashMap<String,Object>();
			resultMap.put("result", "未拥有此权限！");
			return resultMap;
		}
		return puv;
	}
	
	@RequestMapping("/pms/role_show")
	@ResponseBody
	public PmsRoleVo roleShow(ModelMap map,int f_prole_id) {
		PmsRoleVo prv = pmsServiceBean.findRoleById(f_prole_id);
		return prv;
	}
	
	@RequestMapping("/pms/attribute_show")
	@ResponseBody
	public PmsAttributeVo attributeShow(ModelMap map, int f_pa_id) {
		PmsAttributeVo pav = pmsServiceBean.findAttributeById(f_pa_id);
		return pav;
	}
	
	@RequestMapping("/pms/user_edit")
	@ResponseBody
	public Object userEdit(ModelMap map, PmsUserVo puv){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int count = pmsServiceBean.findUserIsExist(puv);
		if (count>0) {
			resultMap.put("success", false);
			resultMap.put("result","用户名已存在!");
		}else {
			int flag = pmsServiceBean.updateUser(puv);
			if(flag>0) {
				resultMap.put("success", true);
				resultMap.put("result","修改成功!");
			} else {
				resultMap.put("success", false);
				resultMap.put("result","修改用户记录失败!flag="+flag);
			}
		}
		return resultMap;
	}

	/**
	 * 新版修改密码
	 * @param map
	 * @param puv
	 * @return
	 */

	@RequestMapping("/pms/userPwd_edit")
	@ResponseBody
	public Object userPwdEdit(ModelMap map, PmsUserVo puv){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		PmsUserVo userVo = pmsServiceBean.findUser(puv);
		if(userVo == null || userVo.getRoleIds() == null || userVo.getRoleIds().trim().length()==0) {
			resultMap.put("status", "error");
			resultMap.put("result", "用户名或密码错误!");
			return resultMap;
		}else{
			int flag = pmsServiceBean.updateUser(userVo);
			if(flag>0) {
				resultMap.put("success", true);
				resultMap.put("result","修改成功!");
			} else {
				resultMap.put("success", false);
				resultMap.put("result","修改用户记录失败!flag="+flag);
			}
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/role_edit")
	@ResponseBody
	public Object roleEdit(ModelMap map, PmsRoleVo prv) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int count = pmsServiceBean.findRoleIsExist(prv);
		if (count>0) {
			resultMap.put("success", false);
			resultMap.put("result","角色已存在!");
		} else {
			int flag = pmsServiceBean.updateRole(prv);
			if(flag>0) {
				resultMap.put("success", true);
				resultMap.put("result","修改成功!");
			} else {
				resultMap.put("success", false);
				resultMap.put("result","修改角色失败!flag="+flag);
			}
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/attribute_edit")
	@ResponseBody
	public Object attributeEdit(ModelMap map, PmsAttributeVo pav) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.updateAttribute(pav);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改属性失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/user_list")
	@ResponseBody
	public Object userList(HttpSession session, PmsUserVo userVo, int page,int rows){
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		userVo.setOrgId(puv.getOrgId());
		Map<String,Object> userListMap = pmsServiceBean.findUserList(ConstantUtils.isSuperAdmin(puv.getRoleIds()),userVo, page, rows);
		return userListMap;
	}
	
	
	@RequestMapping("/pms/role_list")
	@ResponseBody
	public Object roleList(HttpSession session, PmsRoleVo roleVo, int page, int rows) {
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		Map<String,Object> roleListMap = pmsServiceBean.findRoleList(ConstantUtils.isSuperAdmin(puv.getRoleIds()),puv.getOrgId(),roleVo,page,rows);
		return roleListMap;
	}
	
	@RequestMapping("/pms/attribute_list")
	@ResponseBody
	public Object attributeList(ModelMap map,int f_pa_resourceId,int page,int rows) {
		Map<String , Object> attributeListMap = pmsServiceBean.findAttributeList(f_pa_resourceId,page,rows);
		return attributeListMap;
	}
	
	@RequestMapping("/pms/del_user")
	@ResponseBody
	public Object delUser(int f_pu_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.delUserStatus(f_pu_id);
		resultMap.put("resultTitle", "删除结果");
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除记录成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除记录失败!");
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/del_role")
	@ResponseBody
	public Object delRole(int f_prole_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.delRoleStatus(f_prole_id);
		resultMap.put("resultTitle", "删除结果");
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除角色成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除角色失败!");
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/del_attribute")
	@ResponseBody
	public Object delAttribute(int f_pa_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.delAttributeStatus(f_pa_id);
		resultMap.put("resultTitle", "删除结果");
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除属性成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除属性失败!");
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/user_add")
	@ResponseBody
	public Object userAdd(HttpSession session, PmsUserVo userVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		userVo.setOrgId(puv.getOrgId());
		int flag = pmsServiceBean.addUser(ConstantUtils.isSuperAdmin(puv.getRoleIds()),userVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增用户记录成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","新增用户记录失败!flag="+flag);
		}
		return resultMap;
	}

	@RequestMapping("/pms/role_add")
	@ResponseBody
	public Object roleAdd(HttpSession session, PmsRoleVo roleVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		int count = pmsServiceBean.findRoleIsExist(roleVo);
		if(count > 0) {
			resultMap.put("success", false);
			resultMap.put("result","角色名已存在!");
		} else {
			int flag = pmsServiceBean.addRole(ConstantUtils.isSuperAdmin(puv.getRoleIds()),roleVo,puv.getOrgId());
			if(flag>0) {
				resultMap.put("success", true);
				resultMap.put("result","新增角色成功!");
			} else {
				resultMap.put("success", false);
				resultMap.put("result","新增角色失败!flag="+flag);
			}
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/attribute_add")
	@ResponseBody
	public Object attributeAdd(ModelMap map, PmsAttributeVo pav) {
		Map<String,Object> resultMap = new HashMap<String, Object>();
		int flag = pmsServiceBean.addAttribute(pav);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增属性成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","新增属性失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/resource_list")
	@ResponseBody
	public Object resourceList(ModelMap map, PmsResourceVo prv) {
		List<PmsZTreeVo> ptv = new ArrayList<PmsZTreeVo>();
		ptv = pmsServiceBean.selectResourceList(prv);
		return ptv;
	}
	
	@RequestMapping("/pms/org_list")
	@ResponseBody
	public Object orgList(HttpSession session) {
		List<PmsZTreeVo> ptv = new ArrayList<PmsZTreeVo>();
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		ptv = pmsServiceBean.selectOrgList(puv);
		return ptv;
	}
	
	@RequestMapping("/pms/orgVo_list")
	@ResponseBody
	public Object selectOrgList(HttpSession session,PmsOrgVo pmsOrgVo, int page, int rows) {
		PmsUserVo userVo = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		if(userVo.getParentOrgId() > 0){
			String orgIds = pmsServiceBean.getAuthorityPmsOrgIds(userVo);
			pmsOrgVo.setOrgIds(orgIds);
		}
		Map<String,Object> pmsOrgListMap = new HashMap<String, Object>();
		pmsOrgListMap =  pmsServiceBean.selectOrgList(pmsOrgVo, page, rows);
		
		return pmsOrgListMap;
	}
	
	
	@RequestMapping("/pms/industry_orgVo_list")
	@ResponseBody
	public Object selectIndustryOrgList(HttpSession session,PmsOrgVo pmsOrgVo, int page, int rows) {
		PmsUserVo userVo = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		if(userVo.getParentOrgId() > 0){
			String orgIds = pmsServiceBean.getIndustryAuthorityPmsOrgIds(userVo);
			pmsOrgVo.setOrgIds(orgIds);
		}
		Map<String,Object> pmsOrgListMap = new HashMap<String, Object>();
		pmsOrgListMap =  pmsServiceBean.selectOrgList(pmsOrgVo, page, rows);
		
		return pmsOrgListMap;
	}
	
	
	
	@RequestMapping("/pms/authorize_list")
	@ResponseBody
	public Object authorizeList(HttpSession session) {
		List<PmsZTreeVo> ptvList = new ArrayList<PmsZTreeVo>();
		List<PmsResourceVo> prvList = new ArrayList<PmsResourceVo>();
		List<PmsAttributeVo> pavList = new ArrayList<PmsAttributeVo>();
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		boolean isAdmin = ConstantUtils.isSuperAdmin(puv.getRoleIds());
		if(isAdmin) {
			prvList = pmsServiceBean.selectAllResource();
			pavList = pmsServiceBean.selectAllAttribute();
		} else {
			prvList = pmsServiceBean.selectUserResourceList(puv);
			pavList = pmsServiceBean.selectAttributeList(puv);
		}
		for(int i=0; i<prvList.size();i++){
			PmsZTreeVo ptv = new PmsZTreeVo();
			ptv.setId("r"+prvList.get(i).getF_pr_id());
			ptv.setName(prvList.get(i).getF_pr_name());
			ptv.setpId("r"+prvList.get(i).getF_pr_parentId());
			ptv.setUrl(prvList.get(i).getF_pr_url());
			ptv.setType("r");
			ptv.setNocheck(true);
			ptvList.add(ptv);
		}
		for(int i=0; i<pavList.size();i++) {
			PmsZTreeVo ptv = new PmsZTreeVo();
			ptv.setId("a"+pavList.get(i).getF_pa_id());
			ptv.setName(pavList.get(i).getF_pa_name());
			ptv.setpId("r"+pavList.get(i).getF_pa_resourceId());
			ptv.setType("a");
			ptvList.add(ptv);
		}
		return ptvList;
	}
	
	@RequestMapping("/pms/resource_add")
	@ResponseBody
	public Object resourceAdd(ModelMap map,PmsResourceVo resourceVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.addResource(resourceVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增资源成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","新增资源失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/del_resource")
	@ResponseBody
	public Object delResource(ModelMap map, int f_pr_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.delResourceStatus(f_pr_id);
		resultMap.put("resultTitle", "删除结果");
		if(flag==-1){
			resultMap.put("success", false);
			resultMap.put("result","删除资源失败,此资源下还存在属性!");
		}else{
			if(flag>0) {
				resultMap.put("success", true);
				resultMap.put("result","删除资源成功!");
			} else {
				resultMap.put("success", false);
				resultMap.put("result","删除资源失败!");
			}
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/select_resource")
	@ResponseBody
	public Object selectResource(ModelMap map,int f_pr_id) {
		PmsResourceVo prv = new PmsResourceVo();
		prv = pmsServiceBean.selectResource(f_pr_id);
		return prv;
	}
	
	@RequestMapping("/pms/update_resource")
	@ResponseBody
	public Object updateResource(ModelMap map,PmsResourceVo resourceVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.updateResource(resourceVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改用户记录失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/roleResAtt_update")
	@ResponseBody
	public Object updateRoleResAtt(ModelMap map,int f_prra_roleId,String attributeStr) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.updateRoleResAtt(f_prra_roleId,attributeStr);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改角色权限失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/roleAttribute_list")
	@ResponseBody
	public Object selectRoleAttribute(ModelMap map,int f_prra_roleId) {
		List<PmsRoleResourceAttributeVo> prraList = new ArrayList<PmsRoleResourceAttributeVo>();
		prraList = pmsServiceBean.selectRoleAttribute(f_prra_roleId);
		return prraList;
	}
	
	@RequestMapping("/pms/orgUser_list")
	@ResponseBody
	public Object selectOrgUserList() {
		List<PmsUserVo> puvList = new ArrayList<PmsUserVo>();
		puvList = pmsServiceBean.selectOrgUserList();
		return puvList;
	}

	@RequestMapping("/pms/orgRole_list")
	@ResponseBody
	public Object selectOrgRoleList(HttpSession session) {
		List<PmsRoleVo> prvList = new ArrayList<PmsRoleVo>();
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		prvList = pmsServiceBean.selectOrgRoleList(ConstantUtils.isSuperAdmin(puv.getRoleIds()),puv.getOrgId());
		return prvList;
	}
	
	@RequestMapping("/pms/org_add")
	@ResponseBody
	public Object addOrg(PmsOrgVo pov,String roleListValue, String userListValue,String picJson) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap = pmsServiceBean.addOrg(pov,roleListValue,userListValue,picJson);
		return resultMap;
	}
	
	@RequestMapping("/pms/org_select")
	@ResponseBody
	public Object selectOrg(int f_po_id) {
		PmsOrgVo pov = new PmsOrgVo();
		pov = pmsServiceBean.selectOrg(f_po_id);
		return pov;
	}
	
	@RequestMapping("/pms/orgUser_select")
	@ResponseBody
	public Object selectOrgUser(int f_po_id) {
		List<PmsUserVo> puvList = new ArrayList<PmsUserVo>();
		puvList = pmsServiceBean.selectUserOrg(f_po_id);
		return puvList;
	}
	
	@RequestMapping("/pms/orgRole_select")
	@ResponseBody
	public Object selectOrgRole(int f_po_id) {
		List<PmsOrgRoleVo> porvList = new ArrayList<PmsOrgRoleVo>();
		porvList = pmsServiceBean.selectOrgRole(f_po_id);
		return porvList;
	}
	
	@RequestMapping("/pms/roleOrg_select")
	@ResponseBody
	public Object selectRoleByOrgId(int f_po_id) {
		List<PmsRoleVo> prvList = new ArrayList<PmsRoleVo>();
		prvList = pmsServiceBean.selectRoleByOrgId(f_po_id);
		return prvList;
	}
	@RequestMapping("/pms/org_update")
	@ResponseBody
	public Object updateOrg(PmsOrgVo pov,String roleListValue, String userListValue,String picJson,String picType) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap = pmsServiceBean.updateOrg(pov,roleListValue,userListValue,picJson,picType);
		return resultMap;
	}

	/**
	 * 为行业客户管理修改用户导致组织管理会删除用户专门新增的方法
	 * @param pov
	 * @param roleListValue
	 * @param userListValue
	 * @param picJson
	 * @param picType
	 * @return
	 */
	@RequestMapping("/pms/new_org_update")
	@ResponseBody
	public Object newUpdateOrg(PmsOrgVo pov,String roleListValue, String userListValue,String picJson,String picType) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap = pmsServiceBean.newUpdateOrg(pov,roleListValue,userListValue,picJson,picType);
		return resultMap;
	}
	
	@RequestMapping("/pms/orgUserRole_select")
	@ResponseBody
	public Object selectOrgUserRole(int f_po_id) {
		List<PmsOrgUserRoleVo> pourvList = new ArrayList<PmsOrgUserRoleVo>();
		pourvList = pmsServiceBean.selectOrgUserRole(f_po_id);
		return pourvList;
	}
	
	@RequestMapping("/pms/orgUserRole_add")
	@ResponseBody
	public Object addOrgUserRole(int f_po_id,String userRightValue) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.addOrgUserRole(f_po_id,userRightValue);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","授权成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","授权失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/org_del")
	@ResponseBody
	public Object deleteOrg(int f_po_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.deleteOrg(f_po_id);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","组织删除成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","组织删除失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/org_select_parentId")
	@ResponseBody
	public Object selectOrgListByParentId(HttpSession session, PmsOrgVo pmsOrgVo,int page, int rows) {
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		Map<String,Object> pmsOrgListMap = new HashMap<String, Object>();
		pmsOrgListMap = pmsServiceBean.selectOrgListByParentId(puv, pmsOrgVo,page,rows);
		return pmsOrgListMap;
	}
	
	@RequestMapping("/pms/update_org_status")
	@ResponseBody
	public Object updateOrgStatus(int f_po_id,int f_po_status) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.updateOrgStatus(f_po_id,f_po_status);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改失败!");
		}
		return resultMap;
	}
	
	@RequestMapping("/pms/open_vistual_channel")
	@ResponseBody
	public Object openVistualChannel(PmsOrgVo pmsOrgVo) {
		Map<String,Object> resultMap = pmsServiceBean.openVistualChannel(pmsOrgVo);
		return resultMap;
	}
	
	@RequestMapping("/pms/update_vistual_status")
	@ResponseBody
	public Object updateVistualStatus(PmsOrgVo pmsOrgVo) {
		Map<String,Object> resultMap = pmsServiceBean.updateVistualStatus(pmsOrgVo);
		return resultMap;
	}
	
	@RequestMapping("/pms/select_labelBind")
	@ResponseBody
	public Object selectLabelBind(int f_clo_orgid) {
		List<CmLabelOrgVo> cccList = pmsServiceBean.selectLabelBind(f_clo_orgid);
		return cccList;
	}
	
	@RequestMapping("/pms/update_labelBind")
	@ResponseBody
	public Object updateLabelBind(int f_clo_orgid,String labelStr,String labeldeStr, HttpSession session) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = pmsServiceBean.updateLabelBind(f_clo_orgid,labelStr,labeldeStr,session);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改绑定成功!");
		} else if(flag == -5) {
			resultMap.put("success", false);
			resultMap.put("result","修改绑定失败! 目录权限不足!");
			LOG.debug("修改绑定失败! 目录权限不足!");
		} else{
			resultMap.put("success", false);
			resultMap.put("result","修改绑定失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("hotel/pc/hotel_login")
	public Object hotel_login(ModelMap map,String f_pu_name,String f_pu_pwd,String recode,HttpSession session,HttpServletRequest request){
		Object object = login(map,f_pu_name,f_pu_pwd,recode,session,request);
		if("redirect:main.do".equals(object)){
			object = "redirect:hotel_main.do";
		}
		return object;
	}
	
	@RequestMapping("/pms/product_list")
	@ResponseBody
	public Object productList(HttpSession session) {
		List<PmsZTreeVo> ptv = new ArrayList<PmsZTreeVo>();
		ptv = pmsServiceBean.selectProductList();
		return ptv;
	}

	@RequestMapping("pms/wordList")
	@ResponseBody
	public Boolean selectWords(String value){
		value=value.toLowerCase();
		List<String> wordsList = pmsServiceBean.selectWords();
		Boolean flag= true;
		for (int i = 0; i < wordsList.size(); i++) {
			if(value.contains(wordsList.get(i))){
				LOG.debug("敏感词"+wordsList.get(i));
				flag=false;
				break;
			}
		}
		return flag;
	}
	@RequestMapping("pms/findUserHistoryPWdCount")
	@ResponseBody
	public int findUserHistoryPWdCount(PmsUserVo userVo){
		return pmsServiceBean.findUserHistoryPWdCount(userVo);
	}

	@RequestMapping("pms/findUserHistoryPWdDateCount")
	@ResponseBody
	public HashMap<String, Object> findUserHistoryPWdDateCount(HttpSession session){
		HashMap<String, Object> map = new HashMap<>();
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		String pwd_date = SystemConfigUtils.getSysConfig("pwd_date");
		String pwd_tips_date = SystemConfigUtils.getSysConfig("pwd_tips_date");
		int validDate=parseInt(pwd_date);
		if(validDate<0)
			validDate=0;
		puv.setPwd_date(validDate);
		PmsUserVo latestVo = pmsServiceBean.findLastUserHistoryPwd(puv);
		//有效期间存在数据
		if(latestVo!=null){
			Date date1 = latestVo.getF_pu_createAt();
			Date nowDate = new Date();
			//相差天数
			Long days = (nowDate.getTime()-date1.getTime())/(1000*60*60*24);
			double floor = Math.floor((nowDate.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24 + 0.0));
			int tip_date =parseInt(pwd_tips_date);
			if(tip_date<0){
				tip_date=0;
			}
			if(validDate-tip_date-days<=0){
				map.put("days",validDate-floor);
				map.put("success","true");
			}else{
				map.put("success","false");
			}
		}else {
			map.put("success","false");
		}
		map.put("pwd_date",pwd_date);

		return map;
	}
	@RequestMapping("pms/findUserByName")
	@ResponseBody
	public PmsUserVo findUserByName(PmsUserVo puv){
		PmsUserVo userVo = pmsServiceBean.findUserByName(puv);
		if(userVo==null)
			return null;
		return userVo;
	}

	@RequestMapping("pms/findPhoneByName")
	@ResponseBody
	public HashMap<String, Object> findPhoneByName(PmsUserVo puv){
		HashMap<String, Object> resultMap = new HashMap<>();
		PmsUserVo userVo = pmsServiceBean.findUserByName(puv);
		if(userVo==null){
			resultMap.put("phone","");
			resultMap.put("success","false");
		}else{
			resultMap.put("phone",userVo.getF_pu_phone());
			resultMap.put("success","true");
		}
		return resultMap;


	}

	@RequestMapping("pms/updateUserPwd")
	@ResponseBody
	public HashMap<String, Object> updateUser(PmsUserVo puv,String orderId,int smsType){
		HashMap<String, Object> resultMap = new HashMap<>();
		PmsUserVo resultVo = wechatHotelService.findUserOrgByPhone(puv);
		if(resultVo==null){
			resultMap.put("result","查找不到用户");
			resultMap.put("success","false");
		}else{
			//查找密码
			ReceiveMessage vo = new ReceiveMessage();
			String phones = SystemConfigUtils.getSysConfig("admin_phones");
			String[] phoneArray = phones.split(",");
			phones="";
			String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
					"|(18[0-9])|(19[8,9]))\\d{8}$";
			Pattern p = Pattern.compile(regExp);
			for (int i = 0; i < phoneArray.length; i++) {
				Matcher m = p.matcher(phoneArray[i]);
				if(!m.matches()){
					phoneArray[i]="";
				}
				else{
					phones+=phoneArray[i]+",";
				}
			}
			LOG.debug("phones="+phones);
			phones = phones.substring(0, phones.length() - 1);
			vo.setPhones(phones);
			//String login_type = SystemConfigUtils.getSysConfig("login_type");
			String login_type="1";
			vo.setLogin_type(login_type);
			vo.setSmsType(smsType);
			vo.setLiuliuOrderId(orderId);
			ReceiveMessage receiveMessage = wechatWXService.selectRSMS(vo);
			String pwd = receiveMessage.getContent();
			resultVo.setF_pu_pwd(MD5Util.MD5(pwd));
			pmsServiceBean.updateUserPwd(resultVo);
			resultMap.put("result","已修改");
			resultMap.put("success","true");
		}
		return resultMap;
	}
	@RequestMapping("pms/updateUserStatus")
	@ResponseBody
	public HashMap<String, Object> updateUserStatus(PmsUserVo puv){
		HashMap<String, Object> resultMap = new HashMap<>();
		PmsUserVo resultVo = wechatHotelService.findUserOrgByPhone(puv);
		if(resultVo==null){
			resultMap.put("result","查找不到用户");
			resultMap.put("success","false");
		}else{
			resultVo.setF_pu_status(puv.getF_pu_status());
			pmsServiceBean.updateUserStatus(resultVo);
			resultMap.put("result","已修改");
			resultMap.put("success","true");
		}
		return resultMap;
	}

	@RequestMapping("pms/bindUserPhone")
	@ResponseBody
	public HashMap<String, Object> bindUserPhone(PmsUserVo puv){
		HashMap<String, Object> resultMap = new HashMap<>();
		PmsUserVo userVo = pmsServiceBean.findUser(puv);
		if(userVo == null || userVo.getRoleIds() == null || userVo.getRoleIds().trim().length()==0) {
			resultMap.put("status", "error");
			resultMap.put("msg", "用户名或密码错误!");
		}else{
			String phone=userVo.getF_pu_phone();
			//只有没有手机号的用户才能绑定，否则需要密码+验证码修改手机号
			if(phone==null|| "".equals(phone)){
				//修改手机号
				userVo.setF_pu_phone(puv.getF_pu_phone());
				pmsServiceBean.updateUserStatus(userVo);
				resultMap.put("status", "success");
				resultMap.put("msg", "手机号绑定成功!");

			}else{
				resultMap.put("status", "error");
				resultMap.put("msg", "手机号已绑定!");
			}
		}
		return resultMap;
	}

	@RequestMapping("pms/updateUserPhone")
	@ResponseBody
	public HashMap<String, Object> updateUserPhone(PmsUserVo puv,String newPhone){
		HashMap<String, Object> resultMap = new HashMap<>();
		PmsUserVo userVo = pmsServiceBean.findUser(puv);
		if(userVo==null){
			resultMap.put("status", "error");
			resultMap.put("msg", "用户名或密码错误!");
		}else{
			if(userVo.getF_pu_phone().equals(puv.getF_pu_phone())){
				userVo.setF_pu_phone(newPhone);
				pmsServiceBean.updateUserStatus(userVo);
				resultMap.put("status", "success");
				resultMap.put("msg", "修改手机号成功!");

			}else{
				resultMap.put("status", "error");
				resultMap.put("msg", "未绑定手机号!");
			}
		}

		return resultMap;

	}

	@RequestMapping("pms/findUser")
	@ResponseBody
	public HashMap<String, Object> findUser(PmsUserVo puv){
		HashMap<String, Object> resultMap = new HashMap<>();
		PmsUserVo userVo = pmsServiceBean.findUser(puv);
		if(userVo==null){
			resultMap.put("status", "error");
			resultMap.put("msg", "用户名或密码错误!");
		}else{
			if(userVo.getF_pu_phone().equals(puv.getF_pu_phone())){
				resultMap.put("status", "success");
				resultMap.put("msg", "");
			}else{
				resultMap.put("status", "error");
				resultMap.put("msg", "手机号输入错误");
			}
		}
		return resultMap;
	}
	@RequestMapping("login_message")
	@ResponseBody
	public Object sendMessage(ModelMap map,String f_pu_name,String f_pu_pwd,String recode,HttpSession session,HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String title = session.getServletContext().getInitParameter("title");
		resultMap.put("title", title);
		String code = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(f_pu_name==null && f_pu_pwd==null && recode==null) {//登录
			resultMap.put("status", "login"); //请不要修改此值，会关联引用到PmsAspect类中的安全判断--dpf 2018-10-24
			return resultMap;
		}
		PmsUserVo puv = new PmsUserVo();
		puv.setF_pu_name(f_pu_name);
		ServletContext application = session.getServletContext();
		Object applicationLoginFailLockObject = application.getAttribute("applicationLoginFailLockHashMap");
		HashMap<String,ArrayList<PmsLoginAspectVo>> applicationLoginFailLockHashMap = null;
		if(applicationLoginFailLockObject==null)
			applicationLoginFailLockHashMap = new HashMap<String,ArrayList<PmsLoginAspectVo>>();
		else {
			applicationLoginFailLockHashMap = (HashMap<String,ArrayList<PmsLoginAspectVo>>)applicationLoginFailLockObject;
		}
		ArrayList<PmsLoginAspectVo> loginFailLockCountList = applicationLoginFailLockHashMap.get(f_pu_name);
		if(loginFailLockCountList == null)
			loginFailLockCountList = new ArrayList<PmsLoginAspectVo>();
		String loginFailLockCountStr = SystemConfigUtils.getSysConfig("system_login_fail_lock_count");
		int loginFailLockCount = 5;
		if(loginFailLockCountStr != null && !loginFailLockCountStr.trim().equals(""))
			loginFailLockCount = Integer.parseInt(loginFailLockCountStr);
		if(loginFailLockCountList.size()>=(loginFailLockCount-1)) {
			//登录失败次数过多冻结账号
			PmsUserVo userVo = pmsServiceBean.findUserByName(puv);
			if(userVo == null || userVo.getRoleIds() == null || userVo.getRoleIds().trim().length()==0){
				resultMap.put("status", "error");
				resultMap.put("msg", "用户名错误!");
				return resultMap;
			}else{
				userVo.setF_pu_status(2);
				pmsServiceBean.updateUserStatus(userVo);
				resultMap.put("status", "error");
				resultMap.put("msg", "用户连续登录失败次数已达到限制,已冻结。");
				return resultMap;
			}
		}
		LOG.debug("recode=="+recode);
		LOG.debug("code=="+code);

		if(recode == null || !recode.trim().equals(code)) {
			resultMap.put("status", "error");
			resultMap.put("msg", "图形验证码错误!");
			return resultMap;
		}


		puv.setF_pu_pwd(f_pu_pwd);
		PmsUserVo userVo = pmsServiceBean.findUser(puv);
		if(userVo == null || userVo.getRoleIds() == null || userVo.getRoleIds().trim().length()==0) {
			resultMap.put("status", "error");
			resultMap.put("msg", "用户名或密码错误!");
			return resultMap;
		}
		String phone=userVo.getF_pu_phone();
		String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
				"|(18[0-9])|(19[8,9]))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phone);
		//监狱用户，特殊处理
		/*if("18888888888".equals(phone)){

		}else if(!m.matches() || "".equals(phone)){
			resultMap.put("status", "error");
			resultMap.put("msg", "手机号有误!");
			return resultMap;
		}*/

		String user_ip="";
		try {
			user_ip=HttpGetData.getIpAddr(request);
			session.setAttribute(ConstantUtils.SESSION_USER_IP, user_ip);
		} catch (Exception e) {
			LOG.error("获取ip地址错误",e);
		}

		//管理员角色配置项
		String admin_roleList = SystemConfigUtils.getSysConfig("admin_roleList");
		String[] roleList=admin_roleList.split(",");
		boolean isAdmin=false;
		for (int i = 0; i < roleList.length; i++) {
			String roles=userVo.getRoleIds();
			String[] roleArr = roles.split(",");
			for (int j = 0; j < roleArr.length; j++) {
				if (roleList[i].equals(""+roleArr[j])){
					isAdmin=true;
					break;
				}
			}
		}
		//如果是管理员登录，需要开启ip白名单
		if(isAdmin){
			//管理员ip白名单
			String admin_ipList = SystemConfigUtils.getSysConfig("admin_ipList");
			String[] ipList=admin_ipList.split(",");
			boolean flag=false;
			try {
				//获取用户ip
				String ip = user_ip;
				LOG.debug("user_ip="+user_ip);
				for (int i = 0; i < ipList.length; i++) {
					if(ip.contains(ipList[i])){
						flag=true;
						break;
					}
				}
			}catch (Exception e) {
				LOG.debug("获取用户ip异常");
				e.printStackTrace();
			}
			if (!flag) {
				resultMap.put("status", "error");
				resultMap.put("msg", "未开启管理员ip白名单！");
				return resultMap;
			}
		}

		String pwd_date = SystemConfigUtils.getSysConfig("pwd_date");
		userVo.setPwd_date(parseInt(pwd_date));
		userVo.setF_pu_id(userVo.getF_pu_id());
		int historyPWdCount = pmsServiceBean.findUserHistoryPWdCount(userVo);
		if(historyPWdCount==0){
			resultMap.put("status", "error");
			resultMap.put("msg", parseInt(pwd_date)+"天内未更换密码!");
			//未按时更新密码冻结账号
			userVo.setF_pu_status(2);
			pmsServiceBean.updateUserStatus(userVo);
			return resultMap;
		}
		resultMap.put("status", "success");
		resultMap.put("msg", userVo.getF_pu_phone());
		return resultMap;
	}


}

